﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace Qr.Servce {
    public class AccessToken {

        // 只能服务一个公众号，如需服务多个公众号，则这里的设计应该修改
        private string value;
        private DateTime? acquireTime;

        private static Dictionary<string, AccessToken> _dic;

        public static string GetToken() {
            DeveloperCredential credential = DeveloperCredential.GetItemFromConfig();
            return GetToken(credential.AppId, credential.AppSecret);
        }

        /// <summary>
        /// 获取Token
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static string GetToken(string appId, string appSecret) {

            if (_dic == null) _dic = new Dictionary<string, AccessToken>();

            if (_dic.Keys.Contains(appId)) {
                AccessToken token = _dic[appId];

                if (token.acquireTime.HasValue && !String.IsNullOrEmpty(token.value)) {
                    int seconds = DateTime.Now.Subtract(token.acquireTime.Value).Seconds;
                    if (seconds < 6000) {
                        return token.value;
                    }
                }
            }

            return RefreshToken(appId, appSecret);
        }

        /// <summary>
        /// 刷新Token
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        private static string RefreshToken(string appId, string appSecret) {
            string url = String.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appId, appSecret);

            string jsonString = HttpUtility.Get(url);
            if (jsonString.IndexOf("errcode") >= 0) {
                Log.Info("AccessToken 未获得：" + jsonString);
            }

            JavaScriptSerializer js = new JavaScriptSerializer();
            var rtn = js.Deserialize<Dictionary<string, string>>(jsonString);
            AccessToken token = new AccessToken();
            token.acquireTime = DateTime.Now;
            token.value = rtn["access_token"];
            _dic[appId] = token;

            return token.value;
        }


    }
}